package com.spring02.demo.utils;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.invoke.MethodHandleInfo;
import java.lang.reflect.Method;

public class CGLibDynamicProxy implements MethodInterceptor {

    //被代理的对象
    Object object;
    //通过构造方法给被代理对象赋值
    public CGLibDynamicProxy (Object o){
        this.object = o;
    }

    //产生代理对象
    Object getProxy() {
        Enhancer enhancer = new Enhancer();
        //将被代理对象所在的类设置为父类（代理对象就是被代理对象的子类）
        enhancer.setSuperclass(object.getClass());
        //设置回调
        enhancer.setCallback(this);
        Object proxy = enhancer.create();
        return proxy;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        before();
        Object invoke = method.invoke(object, objects);
        after();
        return invoke;
    }
    private void before(){
        System.out.println("before");
    }
    private void after(){
        System.out.println("after");
    }
}
